import request from './request';
import { v4 as uuidv4 } from 'uuid';

// 登录接口
const LOGIN_API = '/api/hzl/login';
const CHANGE_PASSWORD_API = '/api/hzl/changePassword';

// Token存储键名
const TOKEN_KEY = 'user_token';
const USER_INFO_KEY = 'user_info';
const SESSION_USER_ID_KEY = 'user_session_id';

export interface StoredUserInfo {
  id?: string | number;
  username?: string;
  displayName?: string;
  email?: string;
  roleKey?: string;
  roleName?: string;
  permissions?: string[];
  sessionId?: string;
}

/**
 * 生成/获取当前窗口的 sessionId，确保同账号在不同窗口/浏览器有不同标识
 */
export const ensureSessionUserId = (): string => {
  let sessionId = sessionStorage.getItem(SESSION_USER_ID_KEY);
  if (!sessionId) {
    sessionId = uuidv4();
    sessionStorage.setItem(SESSION_USER_ID_KEY, sessionId);
  }
  return sessionId;
};

/**
 * 用户登录
 */
export const login = async (username: string, password: string): Promise<boolean> => {
  try {
    const response = await request.post(LOGIN_API, {
      username,
      password
    });

    if (response.code === 200 && response.data) {
      const { token, userInfo } = response.data as { token: string; userInfo?: unknown };

      const raw = (userInfo || {}) as Record<string, unknown>;
      const rawPermissions = raw.permissions as unknown;
      let normalizedPermissions: string[];
      if (Array.isArray(rawPermissions)) {
        normalizedPermissions = rawPermissions.filter((p): p is string => typeof p === 'string');
      } else if (typeof rawPermissions === 'string') {
        normalizedPermissions = rawPermissions
          .split(',')
          .map(s => s.trim())
          .filter(Boolean);
      } else {
        normalizedPermissions = ['*'];
      }

      const normalizedUserInfo: StoredUserInfo = {
        id: (raw.id as string | number) ?? (raw._id as string | number),
        username: (raw.username as string) ?? (raw['name'] as string),
        displayName: (raw.displayName as string) ?? (raw['nickname'] as string),
        email: raw.email as string | undefined,
        roleKey: (raw['roleKey'] as string) ?? (raw['role'] as string) ?? (raw['roleName'] as string),
        roleName: (raw['roleName'] as string) ?? (raw['role'] as string),
        permissions: normalizedPermissions,
        sessionId: ensureSessionUserId()
      };

      // 存储 token 和用户信息（sessionStorage 优先，localStorage 作为持久化兼容）
      sessionStorage.setItem(TOKEN_KEY, token);
      sessionStorage.setItem(USER_INFO_KEY, JSON.stringify(normalizedUserInfo));
      localStorage.setItem(TOKEN_KEY, token);
      localStorage.setItem(USER_INFO_KEY, JSON.stringify(normalizedUserInfo));
      
      return true;
    }
    
    return false;
  } catch (error) {
    console.error('Login API error:', error);
    throw error;
  }
};

/**
 * 修改密码
 */
export const changePassword = async (username: string, newPassword: string): Promise<{ code: number; message?: string; data?: Record<string, unknown> }> => {
  try {
    const response = await request.post<Record<string, unknown>>(CHANGE_PASSWORD_API, {
      username,
      newPassword
    });
    
    if (response.code !== 200) {
      throw new Error(response.message || '修改密码失败');
    }
    
    return response;
  } catch (error) {
    console.error('Change password API error:', error);
    throw error;
  }
};

/**
 * 用户登出
 */
export const logout = (): void => {
  sessionStorage.removeItem(TOKEN_KEY);
  sessionStorage.removeItem(USER_INFO_KEY);
  localStorage.removeItem(TOKEN_KEY);
  localStorage.removeItem(USER_INFO_KEY);
  sessionStorage.removeItem(SESSION_USER_ID_KEY);
};

/**
 * 获取用户Token
 */
export const getToken = (): string | null => {
  return sessionStorage.getItem(TOKEN_KEY) || localStorage.getItem(TOKEN_KEY);
};

/**
 * 获取用户信息
 */
export const getUserInfo = (): StoredUserInfo | null => {
  const userInfoStr = sessionStorage.getItem(USER_INFO_KEY) || localStorage.getItem(USER_INFO_KEY);
  if (!userInfoStr) return null;
  try {
    const parsed = JSON.parse(userInfoStr) as StoredUserInfo;
    if (parsed) {
      const rawPermissions = (parsed as { permissions?: unknown }).permissions;
      parsed.permissions = Array.isArray(rawPermissions)
        ? rawPermissions.filter((item): item is string => typeof item === 'string')
        : [];
      parsed.sessionId = parsed.sessionId || ensureSessionUserId();
    }
    return parsed;
  } catch (error) {
    console.warn('Failed to parse stored user info, resetting.', error);
    localStorage.removeItem(USER_INFO_KEY);
    return null;
  }
};

/**
 * 检查用户是否已登录
 */
export const isLoggedIn = (): boolean => {
  return !!getToken();
};